import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
/**
 This program implements a multithreaded server that listens to port 8189 and echoes back 
 all client input.
 */
public class Server {
		
	public static void main(String[] args) {
		try {
			int i = 1;
			ServerSocket s = new ServerSocket(8189);

			 try{
				 Process process = null;
				 Properties prop = new Properties(System.getProperties());
				 if (prop.getProperty("os.name").contains("Linux")){
					 String[] cmdarray = {"/bin/sh","clear.sh"};
				    process = Runtime.getRuntime().exec(cmdarray); 
				 }else if(prop.getProperty("os.name").contains("Windows")){
					 //String[] cmdarray = {"cmd","clear.bat"};
				    process = Runtime.getRuntime().exec("cmd.exe /C clear.bat");
				 }
			    	
			    	String ls_str;
			    	DataInputStream ls_in = new DataInputStream(process
							.getInputStream());

					try {
						while ((ls_str = ls_in.readLine()) != null) {
							System.out.println(ls_str);
						}
					} catch (IOException e) {
						System.exit(0);
					}
			 }catch(IOException e){
				 e.printStackTrace();
			 }
			
			while (true) {
				Socket socket = s.accept();
				System.out.println("Spawning " + i + "Connecting socket.");
				Runnable r = new ThreadedEchoHandler(socket,i);
				//r.run();
				Thread t = new Thread(r);
				t.start();
				i++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

/**
 This class handles the client input for one server socket connection. 
 */
class ThreadedEchoHandler implements Runnable {
	private final static String STR_CASH_FILE = "/cashe/";
	private final static String STR_TMP_FILE = "/tmp/";
	private String strCashPath = null;
	private String strTmpPath = null;
	private Socket socket;
	private String strName = null;
	private final static String COMAND_CANCEL = "CANCEL";
	/**
	 Constructs a handler.
	 @param i the socket socket
	 @param c the counter for the handlers (used in prompts)
	 */
	public ThreadedEchoHandler(Socket i,int iIndex) {
		socket = i;
		strCashPath = System.getProperty("user.dir") + STR_CASH_FILE;
		strTmpPath = System.getProperty("user.dir") + STR_TMP_FILE;
		strName = String.valueOf(iIndex) + "tmp.flv";
	}

	public void run() {
		try {

			try {
				//get URL
				final DataInputStream inputStream = new DataInputStream(
						new BufferedInputStream(socket.getInputStream()));
				String strURL = inputStream.readUTF();
				System.out.println("URL: " + strURL);
				
				//use this URL to get file, and save to "viedo" folder
				HttpGet oInstance = new HttpGet();
				try {
				
			      	oInstance.addItem(strURL,strTmpPath + strName);
			      	DataOutputStream outputStream = new DataOutputStream(socket
							.getOutputStream());
					//begin download
					boolean bRet = oInstance.downLoadByList(outputStream);
					//download failure,send  
					if(!bRet){
						outputStream.writeUTF("");
						outputStream.flush();
						outputStream.writeLong(0);
						outputStream.flush();
						socket.close();
						return;
					}
			    }
			    catch (Exception err) {
			      System.out.println(err.getMessage());
			      socket.close();
			      return;
			    } 
			    System.out.println("download complate!");
				// transform the format to 3gp
			    try{
			    	Process process = null;
			    	Properties prop = new Properties(System.getProperties());
			    	if (prop.getProperty("os.name").contains("Linux")){
			    		String[] cmdarray = {"/bin/sh","flvto3gp.sh",strName};
				    	process = Runtime.getRuntime().exec(cmdarray);
			    	}else if(prop.getProperty("os.name").contains("Windows")){
			    		String[] cmdarray = {"cmd.exe", "/C", "start","/I","flvto3gp.bat",strName};
				    	process = Runtime.getRuntime().exec(cmdarray);
			    	}
			    	
			    	String ls_str;
			    	DataInputStream ls_in = new DataInputStream(process
							.getInputStream());

					try {
						while ((ls_str = ls_in.readLine()) != null) {
							System.out.println(ls_str);
						}
					} catch (IOException e) {
						System.exit(0);
					}
			    }catch(IOException e){
			    	e.printStackTrace();
			    }

				// send file name \ size and file to client			
				System.out.println("ready to send file");
				String filePath = strCashPath + strName + ".3gp";
				File file = new File(filePath);
				DataInputStream fileInputStream = new DataInputStream(
						new BufferedInputStream(new FileInputStream(filePath)));
				DataOutputStream outputStream = new DataOutputStream(socket
						.getOutputStream());
				
				outputStream.writeUTF(file.getName());
				outputStream.flush();
				System.out.println("send file name is:" + file.getName());
				long lFileLen = file.length();
				outputStream.writeLong(lFileLen);
				outputStream.flush();
				System.out.println("send file length is:"
						+ String.valueOf(file.length()));
				
				//send file
				int bufferSize = 8096;
				int passedlen = 0;
				byte[] buf = new byte[bufferSize];
				while (true) {
									
					int read = 0;
					if (null != fileInputStream) {
						read = fileInputStream.read(buf);
					}
					//charge whether end of read	
					if (-1 == read) {
						break;
					}
					outputStream.write(buf, 0, read);
					passedlen += read;
					System.out.println("send....current percent:" + (passedlen * 100 / lFileLen)
							+ "%\n");
				}
				outputStream.flush();

				fileInputStream.close();
				socket.close();
				System.out.println("Complete");
			} finally {
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
